﻿using System.Reflection;
using System.Web.Mvc;
using System.Web.Routing;
using Autofac;
using Autofac.Integration.Mvc;
using EFCachingProvider;
using EFCachingProvider.Caching;
using EFCachingProvider.Web;

namespace Web
{

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}.aspx/{action}/{id}", // URL with parameters
                new { controller = "Index", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
                new string[] { "Web.Controllers" }
            );

            routes.MapRoute(
               "Root",
               "",
               new { controller = "Index", action = "Index" },
                new string[] { "Web.Controllers" }
               );
        }

        protected void Application_Start()
        {
            //依赖注入
            var builder = new ContainerBuilder();
            //Register Controllers
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            //Register Model Binders
            builder.RegisterModelBinders(Assembly.GetExecutingAssembly());

            builder.RegisterModule(new AutofacWebTypesModule());
            //builder.RegisterSource(new ViewRegistrationSource());
            //   builder.RegisterModelBinderProvider();
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            //向mvc中添加 下拉框等扩展
            ModelMetadataProviders.Current = new FieldTemplateMetadataProvider();

            //asp.net httpContext 缓存
            //EFCachingProviderConfiguration.DefaultCache = new AspNetCache);
            //数据库依赖缓存 有延时 可以在web.config中设置 但是小于500毫秒 好像就不起作用了
            //EFCachingProviderConfiguration.DefaultCache = new AspNetCacheBroker();
            //纯内存缓存
            EFCachingProviderConfiguration.DefaultCache = new InMemoryCache();
            EFCachingProviderConfiguration.DefaultCachingPolicy = CachingPolicy.CacheAll;

        }
    }
}